<?php

namespace ShopEM\Http\Controllers\Shop\V1;

use Illuminate\Http\Request;
use ShopEM\Http\Controllers\Shop\ErpBaseController;
use ShopEM\Models\ErpConflictList;
use ShopEM\Repositories\ErpMessageRepository;
use ShopEM\Services\Seller\SellerUserService;
use ShopEM\Repositories\ErpSalesOrderRepository;
use ShopEM\Models\UserAccount;
use ShopEM\Services\Coding\CodingService;
use ShopEM\Models\ErpBusines;
use ShopEM\Repositories\ErpSearchPlanRepository;
use ShopEM\Repositories\UserAccountRepository;
use ShopEM\Models\ErpSalesMan;
use ShopEM\Models\ErpSupplier;
use ShopEM\Models\ErpStorehouse;
use ShopEM\Models\ErpSalesOrder;
use ShopEM\Models\ErpSalesOrderDetail;
use ShopEM\Models\ErpPurchaseReceipt;
use ShopEM\Models\ErpPurchaseReceiptDetail;
use ShopEM\Models\ErpCustomer;
use ShopEM\Models\ErpProvince;
use Illuminate\Support\Facades\DB;
use ShopEM\Repositories\ErpRoleRepository;
use ShopEM\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
use ShopEM\Models\ErpCourier;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use ShopEM\Repositories\ErpBusinesRepository;
use ShopEM\Repositories\ErpBusineLogRepository;
use ShopEM\Jobs\ErpBusineLogJob;

class ErpSalesOrderController extends ErpBaseController
{
    /**
     * 销售订单 - 方案请求
     * @Author Lzt
     */
    public function list(Request $request, ErpSalesOrderRepository $repository)
    {
        $start_time = microtime(true);
        $data = $request->all();
    
        $plan_field = $data['plan_field']??[];
        $plan_field_count=count($plan_field);

        $shop_ids = $data['shop_ids']??[];
        $is_count_summary = $data['is_count_summary']??"";
        //获取用户标识
        $user_id = $this->user->id;
        if (empty($user_id)) {
            return $this->resSuccess([
                'list' => [],
                'field' => $repository->erpListShowFields(),
                'search' => $repository->listSearchFields(),
            ]);
        }

        $phone = $this->user->mobile;
        if (empty($phone)) {
            return $this->resSuccess([
                'list' => [],
                'field' => $repository->erpListShowFields(),
                'search' => $repository->listSearchFields(),
            ]);
        }

         // 获取当前url
        $path = $request->path();
        $param = $request->all();
        try {
            // 打印日志
            $busine_id = (new ErpBusinesRepository())->first(['busines_coding' => "salesOrder"])->id ?? '';
                $ErpBusineLogRepository =  (new ErpBusineLogRepository())->save(['busine_id'=>$busine_id,'name'=>'销售订单-列表','transmission'=>$param,'seller_accounts_id'=>$this->user->id,'seller_accounts_source'=>7,'url'=>$path,'is_success'=>2]);

            //需要转换特殊字段
            $time_arr = ['em_erp_sales_orders.created_at','em_erp_sales_orders.updated_at','em_erp_sales_orders.review_date','em_erp_sales_orders.shipment_date','em_erp_sales_orders.sales_date'];
            $sql ="";
            $res = new ErpSalesOrder;

            $busines_coding = "salesOrder";
            //获取当前用户的有效区域
            $ErpRoleRepository = new ErpRoleRepository;
            if (count($shop_ids)!=0) {
                $shopRoleList = $ErpRoleRepository->shopRoleList($phone,$busines_coding);
                if (empty($shopRoleList)) {
                    return $this->resSuccess([
                        'list' => [],
                        'field' => $repository->erpListShowFields(),
                        'search' => $repository->listSearchFields(),
                    ]);
                }
                $where = [];
                foreach ($shopRoleList as $k => $v) {
                    if (in_array($v['shop_id'],$shop_ids)) {
                        if ($v['is_visible']==1) {
                            $where[] = '( em_erp_sales_orders.shop_id = '.$v['shop_id'].' )';
                        }else if ($v['is_visible']==2){
                            //可见自己的时候必须是销售员
                            $sales_man_id = ErpSalesMan::select('erp_sales_mans.id')->where(['erp_sales_mans.user_id' => $user_id,'erp_sales_mans.type' => "A",'shops.id' => $v['shop_id']])
                                            ->leftJoin('shops','shops.organization_coding','=','erp_sales_mans.organization_coding')
                                            ->first();
                            if (!empty($sales_man_id)) {
                                $where[] = '( em_erp_sales_orders.shop_id = '.$v['shop_id'].' and em_erp_sales_orders.seller_accounts_source = 7 and em_erp_sales_orders.sales_man_id = '.$sales_man_id['id'].')';
                            }
                        }
                    }
                }
                if (count($where) != 0) {
                    $str = '('.implode(' or ', $where).')';
                    $res =  $res->whereRaw($str);
                }else{
                    //全部不可见
                    return $this->resSuccess([
                        'list' => [],
                        'field' => $repository->erpListShowFields(),
                        'search' => $repository->listSearchFields(),
                    ]);
                }
            }else{
                $shopRoleList = $ErpRoleRepository->defaultInfoRole($phone,$busines_coding);
                if (empty($shopRoleList)) {
                    return $this->resSuccess([
                        'list' => [],
                        'field' => $repository->erpListShowFields(),
                        'search' => $repository->listSearchFields(),
                    ]);
                }
                //区域id
                $shop_id = $shopRoleList['shop_id'];
                $organization_coding = $shopRoleList['organization_coding'];
                if (empty($shop_id)) {
                    return $this->resSuccess([
                        'list' => [],
                        'field' => $repository->erpListShowFields(),
                        'search' => $repository->listSearchFields(),
                    ]);
                }
                //is_visible = 1 可见全部 is_visible=2 可见自己 is_visible =3 不可见
                if ($shopRoleList['is_visible'] == 1) {
                    $res = $res->where(['erp_sales_orders.shop_id' =>$shop_id]);
                }else if ($shopRoleList['is_visible'] == 2) {
                    //可见自己的时候必须是销售员
                    $sales_man_id = ErpSalesMan::where(['user_id' => $user_id,'type' => "A",'organization_coding' => $organization_coding])->first();
                    if (empty($sales_man_id)) {
                        return $this->resSuccess([
                            'list' => [],
                            'field' => $repository->erpListShowFields(),
                            'search' => $repository->listSearchFields(),
                        ]);
                    }

                    $res = $res->where(['erp_sales_orders.shop_id' =>$shop_id,'erp_sales_orders.seller_accounts_source'=>7,'erp_sales_orders.sales_man_id' =>$sales_man_id['id']]);
                }else{
                    return $this->resSuccess([
                        'list' => [],
                        'field' => $repository->erpListShowFields(),
                        'search' => $repository->listSearchFields(),
                    ]);
                }
                $shop_ids[] = $shop_id;
            }
            
            if ($plan_field_count > 0) {
                $filterPlan = new ErpSearchPlanRepository;
                $sql =$filterPlan->filterPlan($plan_field,$time_arr);
                if ($sql === false ) {
                    return $this->resSuccess("信息有误");
                }else{            
                    if (!empty($sql)) {
                        $res =  $res->whereRaw($sql);
                    }
                }
            }

            $res = $res
                ->leftJoin('erp_sales_order_details','erp_sales_orders.id','=','erp_sales_order_details.sales_order_id')
                ->leftJoin('goods','goods.id','=','erp_sales_order_details.goods_id')
                ->leftJoin('shops','shops.id','=','erp_sales_orders.shop_id')
                ->leftJoin('erp_sales_mans','erp_sales_mans.id','=','erp_sales_orders.sales_man_id')
                ->leftJoin('user_accounts','erp_sales_mans.user_id','=','user_accounts.id')
                ->leftJoin('wx_userinfos','wx_userinfos.user_id','=','user_accounts.id')
                ->leftJoin('seller_infos','seller_infos.merchant_number','=','erp_sales_order_details.merchant_number')
                ->leftJoin('erp_storehouse','erp_storehouse.id','=','erp_sales_order_details.store_id')
                ->leftJoin('erp_sales_shipments','erp_sales_shipments.id','=','erp_sales_orders.sales_shipment_id')
                ->leftJoin('erp_province','erp_province.id','=','erp_sales_orders.province')
                ->leftJoin('erp_courier','erp_courier.id','=','erp_sales_orders.transport_id');
            if (!empty($is_count_summary)) {
                $count = $res->groupBy('erp_sales_orders.id')->select(DB::raw('COUNT(*) as count'))->get()->count();   
                return $count;
            }
            $total = clone $res;
            $total1 = clone  $res;
            $total3 = clone  $res;

            //统计数量
            $sum_total = $total->select('erp_sales_order_details.sales_num')->groupBy('erp_sales_order_details.id')->get(); 
            $sum = [];
            if (empty($sum_total)) {
                $sum['sales_num'] = 0;//数量
            }else{
                $sum['sales_num'] = $sum_total->sum('sales_num');
            }

            $sales_orders = $total1->select(DB::raw("IFNULL(em_erp_sales_orders.all_profit, 0) as all_profit, IFNULL(em_erp_sales_orders.all_total, 0) as all_total"))->groupBy('erp_sales_orders.id')->get();
            if (empty($sales_orders)) {
                $sum['all_profit'] = 0;
                $sum['all_total'] =  0;
            }else{
                $sum['all_profit'] = $sales_orders->sum('all_profit');//利润
                $sum['all_total'] = $sales_orders->sum('all_total');//金额
            }


            $sales = $total3->select(DB::raw('IFNULL(em_erp_sales_orders.freight, 0) as freight'))->where('erp_sales_orders.freight',"!=","")->groupBy('erp_sales_orders.id')->get();

            if (empty($sales)) {
                $sum['freight'] =  0;
            }else{
                $sum['freight'] = $sales->sum('freight');//运费
            }
            // 您的查询代码
            $res = $res->select('erp_sales_orders.*','shops.shop_name as shop_name','wx_userinfos.nickname as sales_man_name','erp_storehouse.name as store_name','goods.crm_number','erp_sales_order_details.wine_style_name','erp_sales_order_details.year_name','erp_sales_order_details.size_name','erp_sales_order_details.inventory_unit_name','erp_sales_order_details.sales_num','erp_sales_order_details.cost_price','erp_sales_order_details.sales_price','erp_sales_order_details.total','seller_infos.merchant_name','erp_sales_order_details.note as detail_note','erp_sales_order_details.goods_id','seller_infos.merchant_number','seller_infos.id as merchant_id','erp_sales_shipments.invoice_number as relevance_invoice_number','erp_sales_order_details.inventory_status','erp_province.name as province_name','erp_courier.name as transport_name','erp_sales_order_details.old_cost_price','shops.sys_mbol','erp_sales_order_details.wine_style_wine_ch','erp_sales_order_details.wine_style_wine_en','erp_sales_order_details.id as details_id','goods.goods_name','erp_sales_order_details.profit','erp_sales_orders.invoice_water_number')
                ->groupBy('erp_sales_order_details.id')->groupBy('erp_sales_orders.id')
                ->orderBy('erp_sales_orders.id','desc')
                ->orderBy('erp_sales_order_details.id','asc')
                ->paginate($data['per_page'] ?? config('app.per_page'));
            
            if (!empty($res)) {
                //上下id一样的去除部分
                foreach ($res as $k => $v) {
                    if ($k == 0) {
                        continue;
                    }
                    $k1 = $k-1;              
                    if ($res[$k]['id'] == $res[$k1]['id']) {
                        $v->status = "";
                        $v->shipment_status = "";
                        $v->down_status = "";
                        $v['invoice_number'] = "";
                        $v['shop_name'] = "";
                        $v['sales_man_name'] = "";              
                        $v['all_total'] = "";
                        $v['all_num'] = "";
                        $v['all_profit'] = "";
                        $v['sales_date'] = null;
                        $v['shipment_date'] = null;
                        $v['shipment_status_name'] = "";
                        $v['information'] = "";
                        $v['customer_name'] = "";
                        $v['phone'] = "";
                        $v['province_name'] = "";
                        $v['address'] = "";
                        $v['transport_name'] = "";
                        $v['freight'] = "";
                        $v['freight_number'] = "";
                        $v['note'] = "";
                        $v['status_name'] = "";
                        $v['review_date'] = null;
                        $v['created_at'] = null;
                        $v['updated_at'] = null;
                        $v['down_status_name'] = "";
                    }
                }
            }
            // 回调成功写入日志
            (new ErpBusineLogRepository())->save(['id'=>$ErpBusineLogRepository['id'],'is_success'=>1]);

            $end_time = microtime(true);
            $execution_time = $end_time - $start_time;
//            fieldsToConvert(['sales_num', 'profit', 'cost_price'], $res);
//            fieldsToConvert(['sales_num', 'profit', 'all_profit', 'all_num', 'freight'], $res);
            return $this->resData([
            // return $this->resSuccess([
                'search' => $repository->listSearchFields($shop_ids),
                'list' => $res,
                'field' => $repository->erpListShowFields(),
                'execution_time'=>$execution_time,
                'sum'=> $sum,
            ]);
        }catch (\Exception $e2) {
             // 报错写入日志
            (new ErpBusineLogRepository())->save(['id'=>$ErpBusineLogRepository['id'],'returnTransmission'=> $e2->getMessage(),'is_success'=>3]);

            return $this->resFailed(600, '服务器错误，联系管理员');
        }      

    }

    /**
     * 销售订单 - 方案请求
     * @Author Lzt
     */
    public function listV1(Request $request, ErpSalesOrderRepository $repository)
    {
        $start_time = microtime(true);
        $data = $request->all();
    
        $plan_field = $data['plan_field']??[];
        $plan_field_count=count($plan_field);

        $shop_ids = $data['shop_ids']??[];
        $is_count_summary = $data['is_count_summary']??"";
        //获取用户标识
        $user_id = $this->user->id;
        if (empty($user_id)) {
            return $this->resSuccess([
                'list' => [],
                'field' => $repository->erpListShowFields(),
                'search' => $repository->listSearchFields(),
            ]);
        }

        $phone = $this->user->mobile;
        if (empty($phone)) {
            return $this->resSuccess([
                'list' => [],
                'field' => $repository->erpListShowFields(),
                'search' => $repository->listSearchFields(),
            ]);
        }

         // 获取当前url
        $path = $request->path();
        $param = $request->all();
        try {
            // 打印日志
            $busine_id = (new ErpBusinesRepository())->first(['busines_coding' => "salesOrder"])->id ?? '';
                $ErpBusineLogRepository =  (new ErpBusineLogRepository())->save(['busine_id'=>$busine_id,'name'=>'销售订单-列表','transmission'=>$param,'seller_accounts_id'=>$this->user->id,'seller_accounts_source'=>7,'url'=>$path,'is_success'=>2]);

            //需要转换特殊字段
            $time_arr = ['em_erp_sales_orders.created_at','em_erp_sales_orders.updated_at','em_erp_sales_orders.review_date','em_erp_sales_orders.shipment_date','em_erp_sales_orders.sales_date'];
            $sql ="";
            $res = new ErpSalesOrder;

            $busines_coding = "salesOrder";
            //获取当前用户的有效区域
            $ErpRoleRepository = new ErpRoleRepository;
            if (count($shop_ids)!=0) {
                $shopRoleList = $ErpRoleRepository->shopRoleList($phone,$busines_coding);
                if (empty($shopRoleList)) {
                    return $this->resSuccess([
                        'list' => [],
                        'field' => $repository->erpListShowFields(),
                        'search' => $repository->listSearchFields(),
                    ]);
                }
                $where = [];
                foreach ($shopRoleList as $k => $v) {
                    if (in_array($v['shop_id'],$shop_ids)) {
                        if ($v['is_visible']==1) {
                            $where[] = '( em_erp_sales_orders.shop_id = '.$v['shop_id'].' )';
                        }else if ($v['is_visible']==2){
                            //可见自己的时候必须是销售员
                            $sales_man_id = ErpSalesMan::select('erp_sales_mans.id')->where(['erp_sales_mans.user_id' => $user_id,'erp_sales_mans.type' => "A",'shops.id' => $v['shop_id']])
                                            ->leftJoin('shops','shops.organization_coding','=','erp_sales_mans.organization_coding')
                                            ->first();
                            if (!empty($sales_man_id)) {
                                $where[] = '( em_erp_sales_orders.shop_id = '.$v['shop_id'].' and em_erp_sales_orders.seller_accounts_source = 7 and em_erp_sales_orders.sales_man_id = '.$sales_man_id['id'].')';
                            }
                        }
                    }
                }
                if (count($where) != 0) {
                    $str = '('.implode(' or ', $where).')';
                    $res =  $res->whereRaw($str);
                }else{
                    //全部不可见
                    return $this->resSuccess([
                        'list' => [],
                        'field' => $repository->erpListShowFields(),
                        'search' => $repository->listSearchFields(),
                    ]);
                }
            }else{
                $shopRoleList = $ErpRoleRepository->defaultInfoRole($phone,$busines_coding);
                if (empty($shopRoleList)) {
                    return $this->resSuccess([
                        'list' => [],
                        'field' => $repository->erpListShowFields(),
                        'search' => $repository->listSearchFields(),
                    ]);
                }
                //区域id
                $shop_id = $shopRoleList['shop_id'];
                $organization_coding = $shopRoleList['organization_coding'];
                if (empty($shop_id)) {
                    return $this->resSuccess([
                        'list' => [],
                        'field' => $repository->erpListShowFields(),
                        'search' => $repository->listSearchFields(),
                    ]);
                }
                //is_visible = 1 可见全部 is_visible=2 可见自己 is_visible =3 不可见
                if ($shopRoleList['is_visible'] == 1) {
                    $res = $res->where(['erp_sales_orders.shop_id' =>$shop_id]);
                }else if ($shopRoleList['is_visible'] == 2) {
                    //可见自己的时候必须是销售员
                    $sales_man_id = ErpSalesMan::where(['user_id' => $user_id,'type' => "A",'organization_coding' => $organization_coding])->first();
                    if (empty($sales_man_id)) {
                        return $this->resSuccess([
                            'list' => [],
                            'field' => $repository->erpListShowFields(),
                            'search' => $repository->listSearchFields(),
                        ]);
                    }

                    $res = $res->where(['erp_sales_orders.shop_id' =>$shop_id,'erp_sales_orders.seller_accounts_source'=>7,'erp_sales_orders.sales_man_id' =>$sales_man_id['id']]);
                }else{
                    return $this->resSuccess([
                        'list' => [],
                        'field' => $repository->erpListShowFields(),
                        'search' => $repository->listSearchFields(),
                    ]);
                }
                $shop_ids[] = $shop_id;
            }
            
            if ($plan_field_count > 0) {
                $filterPlan = new ErpSearchPlanRepository;
                $sql =$filterPlan->filterPlan($plan_field,$time_arr);
                if ($sql === false ) {
                    return $this->resSuccess("信息有误");
                }else{            
                    if (!empty($sql)) {
                        $res =  $res->whereRaw($sql);
                    }
                }
            }

            $res = $res
                ->leftJoin('erp_sales_order_details','erp_sales_orders.id','=','erp_sales_order_details.sales_order_id')
                ->leftJoin('goods','goods.id','=','erp_sales_order_details.goods_id')
                ->leftJoin('shops','shops.id','=','erp_sales_orders.shop_id')
                ->leftJoin('erp_sales_mans','erp_sales_mans.id','=','erp_sales_orders.sales_man_id')
                ->leftJoin('user_accounts','erp_sales_mans.user_id','=','user_accounts.id')
                ->leftJoin('wx_userinfos','wx_userinfos.user_id','=','user_accounts.id')
                ->leftJoin('seller_infos','seller_infos.merchant_number','=','erp_sales_order_details.merchant_number')
                ->leftJoin('erp_storehouse','erp_storehouse.id','=','erp_sales_order_details.store_id')
                ->leftJoin('erp_sales_shipments','erp_sales_shipments.id','=','erp_sales_orders.sales_shipment_id')
                ->leftJoin('erp_province','erp_province.id','=','erp_sales_orders.province')
                ->leftJoin('erp_courier','erp_courier.id','=','erp_sales_orders.transport_id');
            if (!empty($is_count_summary)) {
                $count = $res->groupBy('erp_sales_orders.id')->select(DB::raw('COUNT(*) as count'))->get()->count();   
                return $count;
            }
            $total = clone $res;
            $total1 = clone  $res;
            $total3 = clone  $res;

            //统计数量
            $sum_total = $total->select('erp_sales_order_details.sales_num')->groupBy('erp_sales_order_details.id')->get(); 
            $sum = [];
            if (empty($sum_total)) {
                $sum['sales_num'] = 0;//数量
            }else{
                $sum['sales_num'] = $sum_total->sum('sales_num');
            }

            $sales_orders = $total1->select(DB::raw("IFNULL(em_erp_sales_orders.all_profit, 0) as all_profit, IFNULL(em_erp_sales_orders.all_total, 0) as all_total"))->groupBy('erp_sales_orders.id')->get();
            if (empty($sales_orders)) {
                $sum['all_profit'] = 0;
                $sum['all_total'] =  0;
            }else{
                $sum['all_profit'] = $sales_orders->sum('all_profit');//利润
                $sum['all_total'] = $sales_orders->sum('all_total');//金额
            }


            $sales = $total3->select(DB::raw('IFNULL(em_erp_sales_orders.freight, 0) as freight'))->where('erp_sales_orders.freight',"!=","")->groupBy('erp_sales_orders.id')->get();

            if (empty($sales)) {
                $sum['freight'] =  0;
            }else{
                $sum['freight'] = $sales->sum('freight');//运费
            }
            // 您的查询代码
            $res = $res->select('erp_sales_orders.*','shops.shop_name as shop_name','wx_userinfos.nickname as sales_man_name','erp_storehouse.name as store_name','goods.crm_number','erp_sales_order_details.wine_style_name','erp_sales_order_details.year_name','erp_sales_order_details.size_name','erp_sales_order_details.inventory_unit_name','erp_sales_order_details.sales_num','erp_sales_order_details.cost_price','erp_sales_order_details.sales_price','erp_sales_order_details.total','seller_infos.merchant_name','erp_sales_order_details.note as detail_note','erp_sales_order_details.goods_id','seller_infos.merchant_number','seller_infos.id as merchant_id','erp_sales_shipments.invoice_number as relevance_invoice_number','erp_sales_order_details.inventory_status','erp_province.name as province_name','erp_courier.name as transport_name','erp_sales_order_details.old_cost_price','shops.sys_mbol','erp_sales_order_details.wine_style_wine_ch','erp_sales_order_details.wine_style_wine_en','erp_sales_order_details.id as details_id','goods.goods_name','erp_sales_order_details.profit','erp_sales_orders.invoice_water_number')
                ->groupBy('erp_sales_order_details.id')->groupBy('erp_sales_orders.id')
                ->orderBy('erp_sales_orders.id','desc')
                ->orderBy('erp_sales_order_details.id','asc')
                ->paginate($data['per_page'] ?? config('app.per_page'));
            
            if (!empty($res)) {
                //上下id一样的去除部分
                foreach ($res as $k => $v) {
                    if ($k == 0) {
                        continue;
                    }
                    $k1 = $k-1;              
                    if ($res[$k]['id'] == $res[$k1]['id']) {
                        $v->status = "";
                        $v->shipment_status = "";
                        $v->down_status = "";
                        $v['invoice_number'] = "";
                        $v['shop_name'] = "";
                        $v['sales_man_name'] = "";              
                        $v['all_total'] = "";
                        $v['all_num'] = "";
                        $v['all_profit'] = "";
                        $v['sales_date'] = null;
                        $v['shipment_date'] = null;
                        $v['shipment_status_name'] = "";
                        $v['information'] = "";
                        $v['customer_name'] = "";
                        $v['phone'] = "";
                        $v['province_name'] = "";
                        $v['address'] = "";
                        $v['transport_name'] = "";
                        $v['freight'] = "";
                        $v['freight_number'] = "";
                        $v['note'] = "";
                        $v['status_name'] = "";
                        $v['review_date'] = null;
                        $v['created_at'] = null;
                        $v['updated_at'] = null;
                        $v['down_status_name'] = "";
                    }
                }
            }
            // 回调成功写入日志
            (new ErpBusineLogRepository())->save(['id'=>$ErpBusineLogRepository['id'],'is_success'=>1]);

            $end_time = microtime(true);
            $execution_time = $end_time - $start_time;
            // return 1;
                // return $res->toArray();
            return $this->responseDataCS([
                'search' => $repository->listSearchFields($shop_ids),
                'list' => $res->toArray(),
                'field' => $repository->erpListShowFields(),
                'execution_time'=>$execution_time,
                'sum'=>$sum,
            ]);


            return $execution_time;
            // return $this->resSuccess([
            //     'search' => $repository->listSearchFields($shop_ids),
            //     'list' => $res,
            //     'field' => $repository->erpListShowFields(),
            //     'execution_time'=>$execution_time,
            //     'sum'=>$sum,
            // ]);
        }catch (\Exception $e2) {
             // 报错写入日志
            (new ErpBusineLogRepository())->save(['id'=>$ErpBusineLogRepository['id'],'returnTransmission'=> $e2->getMessage(),'is_success'=>3]);

            return $this->resFailed(600, '服务器错误，联系管理员');
        }      
        
    }


    /**
     * 创建api统一返回数据
     *
     * @Author lzt
     * @return array
     */
    public function responseDataCS($data=[],$code=0,$message='success!')
    {
        $res = [
            'code' => $code,
            'message' => $message,
            'result' => $data,
        ];

        return $res;
    }

    /**
     * 导出
     * @param Request $request
     * @param ErpSalesOrderRepository $repository
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\BinaryFileResponse
     * @Author Eva
     */
    public function export(Request $request, ErpSalesOrderRepository $repository)
    {
        $data = $request->all();

        $plan_field = $data['plan_field']??[];
        $plan_field_count = count($plan_field);
        $shop_ids = $data['shop_ids']??[];
        $is_count_summary = $data['is_count_summary']??"";
        $module_template  = $data['module_template'] ?? [];

        if(!count($module_template)){
            return $this->resFailed(600,'没有默认字段');
        }
        $headings = [
            '销售组织', '销售日期', '商品编码', '单据编码', '单据状态', '销售员' , '联系人' , '酒款名称' , '年份', '规格', '包装',
            '销售数量',  '销售价格', '利润', '成本', '总利润', '总金额', '运输方式', '运费', '运输单号', '库存状态', '备注', '电话', '省份','详细地址',
            '金额', '总数量' , '仓库' , '出库日期', '出库状态', '下推状态', '自提信息', '仓库备注', '创建日期', '更新日期' , '审核日期', '商家'
        ];

       if(count($module_template)){
           $headings =  array_column($module_template, 'label');
       }
        //获取用户标识
        $user_id = $this->user->id;
        if (empty($user_id)) {
            return Excel::download(new UsersExport([], $headings, []), '销售管理-销售订单导出数据'.date('Y-m-d H:i:s').'.xlsx');
        }

        $phone = $this->user->mobile;
        if (empty($phone)) {
            return Excel::download(new UsersExport([], $headings, []), '销售管理-销售订单导出数据'.date('Y-m-d H:i:s').'.xlsx');
        }

        //需要转换特殊字段
        $time_arr = ['em_erp_sales_orders.created_at','em_erp_sales_orders.updated_at','em_erp_sales_orders.review_date','em_erp_sales_orders.shipment_date','em_erp_sales_orders.sales_date'];
        $sql ="";
        $res = new ErpSalesOrder;

        $busines_coding = "salesOrder";
        //获取当前用户的有效区域
        $ErpRoleRepository = new ErpRoleRepository;
        if (count($shop_ids)!=0) {
            $shopRoleList = $ErpRoleRepository->shopRoleList($phone,$busines_coding);
            if (empty($shopRoleList)) {
                return Excel::download(new UsersExport([], $headings, []), '销售管理-销售订单导出数据'.date('Y-m-d H:i:s').'.xlsx');
            }
            $where = [];
            foreach ($shopRoleList as $k => $v) {
                if (in_array($v['shop_id'],$shop_ids)) {
                    if ($v['is_visible']==1) {
                        $where[] = '( em_erp_sales_orders.shop_id = '.$v['shop_id'].' )';
                    }else if ($v['is_visible']==2){
                        //可见自己的时候必须是销售员
                        $sales_man_id = ErpSalesMan::select('erp_sales_mans.id')->where(['erp_sales_mans.user_id' => $user_id,'erp_sales_mans.type' => "A",'shops.id' => $v['shop_id']])
                            ->leftJoin('shops','shops.organization_coding','=','erp_sales_mans.organization_coding')
                            ->first();
                        if (!empty($sales_man_id)) {
                            $where[] = '( em_erp_sales_orders.shop_id = '.$v['shop_id'].' and em_erp_sales_orders.seller_accounts_source = 7 and em_erp_sales_orders.sales_man_id = '.$sales_man_id['id'].')';
                        }
                    }
                }
            }
            if (count($where) != 0) {
                $str = '('.implode(' or ', $where).')';
                $res =  $res->whereRaw($str);
            }else{
                return Excel::download(new UsersExport([], $headings, []), '销售管理-销售订单导出数据'.date('Y-m-d H:i:s').'.xlsx');
            }
        }else{
            $shopRoleList = $ErpRoleRepository->defaultInfoRole($phone,$busines_coding);
            if (empty($shopRoleList)) {
                return Excel::download(new UsersExport([], $headings, []), '销售管理-销售订单导出数据'.date('Y-m-d H:i:s').'.xlsx');

            }
            //区域id
            $shop_id = $shopRoleList['shop_id'];
            $organization_coding = $shopRoleList['organization_coding'];
            if (empty($shop_id)) {
                return Excel::download(new UsersExport([], $headings, []), '销售管理-销售订单导出数据'.date('Y-m-d H:i:s').'.xlsx');
            }
            //is_visible = 1 可见全部 is_visible=2 可见自己 is_visible =3 不可见
            if ($shopRoleList['is_visible'] == 1) {
                $res = $res->where(['erp_sales_orders.shop_id' =>$shop_id]);
            }else if ($shopRoleList['is_visible'] == 2) {
                //可见自己的时候必须是销售员
                $sales_man_id = ErpSalesMan::where(['user_id' => $user_id,'type' => "A",'organization_coding' => $organization_coding])->first();
                if (empty($sales_man_id)) {
                    return Excel::download(new UsersExport([], $headings, []), '销售管理-销售订单导出数据'.date('Y-m-d H:i:s').'.xlsx');
                }

                $res = $res->where(['erp_sales_orders.shop_id' =>$shop_id,'erp_sales_orders.seller_accounts_source'=>7,'erp_sales_orders.sales_man_id' =>$sales_man_id['id']]);
            }else{
                return Excel::download(new UsersExport([], $headings, []), '销售管理-销售订单导出数据'.date('Y-m-d H:i:s').'.xlsx');
            }
            $shop_ids[] = $shop_id;
        }

        if ($plan_field_count > 0) {
            $filterPlan = new ErpSearchPlanRepository;
            $sql =$filterPlan->filterPlan($plan_field,$time_arr);
            if ($sql === false ) {
                return $this->resSuccess("信息有误");
            }else{
                if (!empty($sql)) {
                    $res =  $res->whereRaw($sql);
                }
            }
        }

        $res = $res
            ->leftJoin('erp_sales_order_details','erp_sales_orders.id','=','erp_sales_order_details.sales_order_id')
            ->leftJoin('goods','goods.id','=','erp_sales_order_details.goods_id')
            ->leftJoin('shops','shops.id','=','erp_sales_orders.shop_id')
            ->leftJoin('erp_sales_mans','erp_sales_mans.id','=','erp_sales_orders.sales_man_id')
            ->leftJoin('user_accounts','erp_sales_mans.user_id','=','user_accounts.id')
            ->leftJoin('wx_userinfos','wx_userinfos.user_id','=','user_accounts.id')
            ->leftJoin('seller_infos','seller_infos.merchant_number','=','erp_sales_order_details.merchant_number')
            ->leftJoin('erp_storehouse','erp_storehouse.id','=','erp_sales_order_details.store_id')
            ->leftJoin('erp_sales_shipments','erp_sales_shipments.id','=','erp_sales_orders.sales_shipment_id')
            ->leftJoin('erp_province','erp_province.id','=','erp_sales_orders.province')
            ->leftJoin('erp_courier','erp_courier.id','=','erp_sales_orders.transport_id')
        ;

        if (!empty($is_count_summary)) {
            $count = $res->groupBy('erp_sales_orders.id')->select(DB::raw('COUNT(*) as count'))->get()->count();
            return $count;
        }
        $res = $res->select('erp_sales_orders.*','shops.shop_name as shop_name','wx_userinfos.nickname as sales_man_name','erp_storehouse.name as store_name','goods.crm_number','erp_sales_order_details.wine_style_name','erp_sales_order_details.year_name','erp_sales_order_details.size_name','erp_sales_order_details.inventory_unit_name','erp_sales_order_details.sales_num','erp_sales_order_details.cost_price','erp_sales_order_details.sales_price','erp_sales_order_details.total','seller_infos.merchant_name','erp_sales_order_details.note as detail_note','erp_sales_order_details.goods_id','seller_infos.merchant_number','seller_infos.id as merchant_id','erp_sales_shipments.invoice_number as relevance_invoice_number','erp_sales_order_details.inventory_status','erp_province.name as province_name','erp_courier.name as transport_name','erp_sales_order_details.old_cost_price','shops.sys_mbol','erp_sales_order_details.wine_style_wine_ch','erp_sales_order_details.wine_style_wine_en','erp_sales_order_details.id as details_id','goods.goods_name','erp_sales_order_details.profit')
            ->groupBy('erp_sales_order_details.id')->groupBy('erp_sales_orders.id')
            ->orderBy('erp_sales_orders.id','desc')->paginate(9999999);

        if (!empty($res)) {
            //上下id一样的去除部分
            foreach ($res as $k => $v) {
                $v['seller_accounts_name'] = '';
                $seller_accounts_name = (new UserAccountRepository)->sellerAccountName($v['seller_accounts_id'],$v['seller_accounts_source']);
                if (!empty($seller_accounts_name)) {
                    $v['seller_accounts_name'] = $seller_accounts_name['username'];
                }
                if ($k == 0) {
                    continue;
                }
                $k1 = $k-1;
                if ($res[$k]['id'] == $res[$k1]['id']) {
                    $v->status = "";
                    $v->shipment_status = "";
                    $v->down_status = "";
                    $v['invoice_number'] = "";
                    $v['shop_name'] = "";
                    $v['sales_man_name'] = "";
                    $v['all_total'] = "";
                    $v['all_num'] = "";
                    $v['all_profit'] = "";
                    $v['sales_date'] = null;
                    $v['shipment_date'] = null;
                    $v['shipment_status_name'] = "";
                    $v['information'] = "";
                    $v['customer_name'] = "";
                    $v['phone'] = "";
                    $v['province_name'] = "";
                    $v['address'] = "";
                    $v['transport_name'] = "";
                    $v['freight'] = "";
                    $v['freight_number'] = "";
                    $v['note'] = "";
                    $V['status_name'] = "";
                    $v['review_date'] = null;
                    $v['created_at'] = null;
                    $v['updated_at'] = null;
                    $v['down_status_name'] = "";
                }
            }
        }
        $data = [];
        foreach ($res as $item) {
            $data[] = [
                $item['shop_name'],
                $item['sales_date'],
                $item['crm_number'],
                $item['invoice_number'],
                $item['status_name'],
                $item['sales_man_name'],
                $item['customer_name'],
                $item['wine_style_wine_ch'].$item['wine_style_wine_en'],
                $item['year_name'],
                $item['size_name'],
                $item['inventory_unit_name'],
                $item['sales_num'],
                $item['sales_price'],
                $item['profit'],
                $item['cost_price'],
                $item['all_profit'],
                $item['all_total'],
                $item['transport_name'],
                $item['freight'],
                $item['freight_number'],
                $item['inventory_status'],
                $item['note'],
                $item['phone'],
                $item['province_name'],
                $item['address'],
                $item['total'],
                $item['all_num'],
                $item['store_name'],
                $item['shipment_date'],
                $item['shipment_status_name'],
                $item['down_status_name'],
                $item['information'],
                $item['detail_note'],
                $item['created_at'],
                $item['updated_at'],
                $item['review_date'],
                $item['merchant_name'],
            ];
        }
        // 导出
        return Excel::download(new UsersExport($data, $headings, [], $module_template), '销售订单导出数据'.date('Y-m-d H:i:s').'.xlsx');

    }


    /**
     * 销售订单保存 批量添加
     * @Author Lzt
     */
    public function save(Request $request, ErpSalesOrderRepository $repository)
    {
        $data = $request->all();
        //获取用户标识
        $user_id = $this->user->id;
        if (empty($user_id)) {
            return $this->resFailed(414, '请联系管理员');
        }

        $phone = $this->user->mobile;
        if (empty($phone)) {
            return $this->resFailed(414, '请联系管理员');
        }

        $busines_coding = "salesOrder";

        if (empty($data['shop_id'])) {
            return $this->resFailed(414, '组织为空');
        }
        // 获取当前url
        $path = $request->path();
        $param = $request->all();
        try {
            // 打印日志
            $busine_id = (new ErpBusinesRepository())->first(['busines_coding' => $busines_coding])->id ?? '';
            $ErpBusineLogRepository =  (new ErpBusineLogRepository())->save(['busine_id'=>$busine_id,'name'=>'销售订单-保存','transmission'=>$param,'seller_accounts_id'=>$this->user->id,'seller_accounts_source'=>7,'url'=>$path,'is_success'=>2]);

            if (empty($data['id'])) {
                $shop_id = $data['shop_id'];

            }else{
                $erpSalesOrder = ErpSalesOrder::where(['id' => $data['id']])->first();
                if (empty($erpSalesOrder)) {
                    return $this->resFailed(414, 'id错误');
                }
                $is_lock =$this->OrderIsLock(['shop_id' => $erpSalesOrder->shop_id, 'coding' => $erpSalesOrder->invoice_number]);
                if($is_lock){
                    if($is_lock->user_id != $this->user->id) {
                        return $this->resFailed(414, '该订单已被锁定，不可保存操作');
                    }
                }
                $shop_id = $erpSalesOrder['shop_id'];
            }

            //获取当前用户的区域权限
            $ErpRoleRepository = new ErpRoleRepository;
            $shopRoleList = $ErpRoleRepository->defaultInfoPathShopRole($phone,$busines_coding,$shop_id,$path);

            if (empty($shopRoleList)) {
                return $this->resFailed(414, '没有权限');
            }


            $organization_coding = $shopRoleList['organization_coding'];
            if (empty($organization_coding)) {
                return $this->resFailed(414, '请联系管理员分区域');
            }
            //区域id
            $shop_id = $shopRoleList['shop_id'];
            if (empty($shop_id)) {
                return $this->resFailed(414, '请联系管理员分区域');
            }

            //查看当前手机号是否商家
            $user = UserAccount::select('seller_infos.id','seller_infos.merchant_number')
                ->where('wx_userinfos.user_id',"!=","")
                ->leftJoin('wx_userinfos','wx_userinfos.user_id','=','user_accounts.id')
                ->leftJoin('seller_users','seller_users.phone','=','user_accounts.mobile')
                ->leftJoin('seller_infos','seller_infos.merchant_number','=','seller_users.merchant_number')
                ->where('user_accounts.mobile',$phone)
                ->where('seller_infos.org_number',$organization_coding)
                ->first();

            if (empty($user)) {
                return $this->resFailed(414, '请联系管理员,添加商家档案');
            }

            // 客户规则是否添加
            $busines_customer = "base_customer";
            $busines_customers = ErpBusines::where('busines_coding',$busines_customer)->first();
            if (empty($busines_customers)) {
                return $this->resFailed(403, "请配置客户业务对象");
            }
            $customer_number = (new CodingService)->generaCodingV1($busines_customers['id']);
            if ($customer_number['text'] != "ok") {
                return $this->resFailed(403, "请去配置客户系统编码规则");
            }

            $data['detail_lists'] = $data['detail_lists']??[];

            $data['shop_id']  = $shop_id;

            $status = ""; 

            if(!empty($data['id'])) {
               $ErpSalesOrder = ErpSalesOrder::where(['id' => $data['id'],'shop_id' =>$shop_id])->first();
                if (empty($ErpSalesOrder)) {
                   return $this->resFailed(403, "数据不存在");
                }
                $status = $ErpSalesOrder['status'];
                // if ($ErpSalesOrder['status'] == "B" || $ErpSalesOrder['status'] == "C") {
                //     return $this->resFailed(403, '数据不允许修改');
                // }
            }else{
                $busines_coding = "salesOrder";
                $res = ErpBusines::where('busines_coding',$busines_coding)->first();
                if (empty($res)) {
                    return $this->resFailed(403, "请配置业务对象");
                }

                $invoice_number = (new CodingService)->generaCodingV1($res['id']);
                if ($invoice_number['text'] != "ok") {
                    return $this->resFailed(403, "请去配置客户系统编码规则");
                }
                $invoice_number = $invoice_number['number'];
                $number = $this->getCoding($res['id'],$invoice_number, 1);
                if (empty($number)) {
                     return $this->resFailed(403, "编码规则生成失败");
                }
                $data['invoice_number']  = $number;
                // $data['sales_date']  = date("Y-m-d H:i:s");
                $data['seller_accounts_id'] = $user_id;
                $data['seller_accounts_source']   = 7;
                $data['shipment_status'] = 1;
            }

            if (!empty($data['transport_id'])) {
                //快递方式
                $transport_id = ErpCourier::where(['shop_id'=>$shop_id,'id'=>$data['transport_id'],'status'=>'C'])->first();
        
                if (empty($transport_id)) {
                    return $this->resFailed(414, '快递方式错误');
                }
            }
            

            //获取明细信息 得到数量 金额 利润
            $detail_lists = $data['detail_lists']??[];
            if (count($detail_lists)!=0) {
                $sales_order_id = $data['id']??"";
                $all_total= 0;
                $all_num= 0;
                $all_profit= 0;
                foreach ($detail_lists as $k => $v) {
                     //计算金额
                    if (empty($v['sales_price'])) {
                        $v['sales_price'] = 0;
                    }
                    if (empty($v['cost_price'])) {
                        $v['cost_price'] = 0;
                    }
                    if (empty($v['sales_num'])) {
                        $v['sales_num'] = 0;
                    }
                    $profit = round(($v['sales_price'] - $v['cost_price'])*$v['sales_num'],2);
                    $total = round($v['sales_price']*$v['sales_num'],2);
                    $all_num = $all_num + $v['sales_num'];
                    $all_total = round($all_total + $total,2);
                    $all_profit = round($all_profit + $profit,2);
                }
                $data['all_total'] =$all_total;
                $data['all_num'] =$all_num;
                $data['all_profit'] =$all_profit;
                //验证详情商品
                $processingData =  $repository -> processingData($detail_lists,$shop_id,$organization_coding,$sales_order_id);

                if ($processingData !== true ) {
                    return $this->resFailed(414, $processingData);
                }
            }

            if (!empty($data['province'])) {
                $erpProvince = ErpProvince::where('id',$data['province'])->first();
                if (empty($erpProvince)) {
                    return $this->resFailed(414, '省份错误');
                }
            }

            if (!empty($data['sales_man_id'])) {
                $erpSalesMan = ErpSalesMan::where(['id' => $data['sales_man_id'],'organization_coding' => $organization_coding,'type' => "A"])->first();
                if (empty($erpSalesMan)) {
                    return $this->resFailed(414, '销售员错误');
                }
            }
            
            if (!empty($data['customer_id'])) {
                $erpCustomer = ErpCustomer::where(['id' => $data['customer_id'],'shop_id' => $shop_id,'status' => "C"])->first();
                if (empty($erpCustomer)) {
                    return $this->resFailed(414, '联系人错误');
                }
            }else{
                //客户id不存在 联系人，电话，省份，地址同时存在
                if (!empty($data['customer_name'])&&!empty($data['phone'])&&!empty($data['province'])&&!empty($data['address'])&&!empty($data['sales_man_id'])) {
                     $customer_id = ErpCustomer::where(['contact_person' =>$data['customer_name'],'phone'=> $data['phone'],'province_id' => $data['province'],'address'=> $data['address'],'sale_id' => $data['sales_man_id'],'shop_id' => $shop_id])->first();
                    //不为空就那对应的id
                    if (!empty($customer_id)) {
                        $data['customer_id'] = $customer_id['id'];
                    }else{
                        // 客户规则是否添加
                        $busines_customer = "base_customer";
                        $busines_customers = ErpBusines::where('busines_coding',$busines_customer)->first();
                        if (empty($busines_customers)) {
                            return $this->resFailed(403, "请配置客户业务对象");
                        }
                        $customer_number = (new CodingService)->generaCodingV1($busines_customers['id']);
                        if ($customer_number['text'] != "ok") {
                            return $this->resFailed(403, "请去配置客户系统编码规则");
                        }

                        $create = [
                            'phone'=> $data['phone'],
                            'contact_person'=> $data['customer_name'],
                            'address'=> $data['address'],
                            'coding' => $customer_number['number'],
                            'shop_id' => $shop_id,
                            'sale_id' => $data['sales_man_id'],
                            'province_id' => $data['province'],
                            'status'   => 'C',
                            'review_date'=> date("Y-m-d H:i:s"),
                            'header'=>$data['rise']??'',
                            'tax_id'=>$data['duty']??'',
                            'bank'=>$data['bank']??'',
                            'account'=>$data['account']??'',
                            'email'=>$data['mail']??'',
                            'company_address_phone'=>$data['company_address_phone']??'',
                            'billing_address_phone'=>$data['receiving_address_phone']??'',
                            'invoice_type'=>$data['invoice_type']??'',
                            'invoice_remark'=>$data['invoice_remark']??'',
                            'invoice_serial_number'=>$data['invoice_water_number']??'',
                            'seller_accounts_id'=>$user_id,
                            'seller_accounts_source'=>7
                        ];
                        
                        $customer_id = ErpCustomer::create($create);
                        $data['customer_id'] = $customer_id['id'];
                    }
                }
               
            }
                
            $data['merchant_number'] = $user['merchant_number'];

              
            $res = $repository->save($data,$organization_coding,$status);

            // 回调成功写入日志
            $invoice_number = ErpSalesOrder::where('id',$res)->first();
            (new ErpBusineLogRepository())->save(['id'=>$ErpBusineLogRepository['id'],'returnTransmission'=> $res,'invoice_number'=>$invoice_number['invoice_number'],'is_success'=>1,'shop_id'=>$shop_id]);

            return $this->resSuccess($res,'');
        }catch (\Exception $e2) {
             // 报错写入日志
            (new ErpBusineLogRepository())->save(['id'=>$ErpBusineLogRepository['id'],'returnTransmission'=> $e2->getMessage(),'is_success'=>3]);

            return $this->resFailed(600, '服务器错误，联系管理员');
        } 
    }


    /**
     * 销售订单删除
     * @Author Lzt
     */
    public function delete(Request $request, ErpSalesOrderRepository $repository)
    {
        $data = $request->only('id');
        if (empty($data['id'])) {
            return $this->resFailed(414, 'ID不能为空');
        }
        //获取用户标识
        $user_id = $this->user->id;
        if (empty($user_id)) {
            return $this->resFailed(414, '请联系管理员');
        }

        $phone = $this->user->mobile;
        if (empty($phone)) {
            return $this->resFailed(414, '请联系管理员');
        }

        $busines_coding = "purchaseOrder";
        // 获取当前url
        $path = $request->path();
        $param = $request->all();
        $rep_msg = new ErpMessageRepository();
        try {
            // 打印日志
            $busine_id = (new ErpBusinesRepository())->first(['busines_coding' => $busines_coding])->id ?? '';
            $ErpBusineLogRepository =  (new ErpBusineLogRepository())->save(['busine_id'=>$busine_id,'name'=>'销售订单-删除','transmission'=>$param,'seller_accounts_id'=>$this->user->id,'seller_accounts_source'=>7,'url'=>$path,'is_success'=>2]);

            $id_array = explode(",", $data['id']);
            $id_array = array_unique($id_array);
            $tmp_id    = [];
            $tmp_msg   = [];
            $data_info = ErpSalesOrder::whereIn('id', $id_array)->select('id','shop_id', 'invoice_number')->get()->toArray();
            foreach ($data_info as $item){
                $is_lock =$this->OrderIsLock(['shop_id' => $item['shop_id'], 'coding' => $item['invoice_number']]);
                if($is_lock){
                    if($is_lock->user_id != $this->user->id) {
                        $tmp_id[] = $item['id'];
                        $tmp_msg[] = [
                            'id' => $item['id'],
                            'msg' => '该订单已锁定，不可操作',
                            'name' => '',
                            'coding' => $item['invoice_number'],
                            'commit' => false,
                        ];
                    }
                }
            }
            // 找出差集合，差集合则是需要处理的
            $ids = array_diff($id_array, $tmp_id);

            //查询所有的区域
            //        $ids = explode(",", $data['id']);
            //        $ids = array_unique($ids);
            $ErpSalesOrder = ErpSalesOrder::whereIn('id', $ids)->select('shop_id')->groupBy('shop_id')->get()->toArray();
            if (count($ErpSalesOrder) == 0) {
                return $this->resFailed(414, '数据错误');
            }
            $busines_coding = "salesOrder";
            $business_id = ErpBusines::where('busines_coding',$busines_coding)->first();
            if (empty($business_id)) {
                return $this->resFailed(403, "请配置业务对象");
            }
            $business_id = $business_id['id'];
            // 获取当前url
            $path = $request->path();
           
            //获取当前用户的区域权限
            $ErpRoleRepository = new ErpRoleRepository;
            $shop_id = [];
            foreach ($ErpSalesOrder as $k=> $v) {
                $shopRoleList = $ErpRoleRepository->defaultInfoPathShopRole($phone,$busines_coding,$v['shop_id'],$path);
                if (!empty($shopRoleList)) {
                    $shop_id[] = $v['shop_id'];
                }
                
            }
            if (count($shop_id) == 0) {
                return $this->resFailed(414, '没有权限');
            }

            // 回调成功写入日志
            $shop_list =  ErpSalesOrder::select('id','shop_id')->whereIn('id', $id_array)->get()->toArray();
        
            $res =  $repository->delete($ids,$shop_id);
            // 合并msg
            $res = array_merge($res, $tmp_msg);

            if (empty($res)) {
                return $this->resFailed(414, '没有权限');
            }

            // 回调成功写入日志
            ErpBusineLogJob::dispatch(['repository' => new ErpSalesOrder,'returnTransmission' => $res,'shop_type' => 'shop_id','busine_id'=>$busine_id,'name'=>'销售订单-删除','transmission'=>$param,'seller_accounts_id'=>$this->user->id,'seller_accounts_source'=>7,'url'=>$path,'is_success'=>1,'shop_list'=>$shop_list]);

            if (count($res) ==1) {
                if ($res[0]['commit'] == false) {
                    return $this->resFailed(414, $res[0]['msg']);
                }else{
                    $erp_msg_res = $rep_msg->getMsg('erp_sales_order', 'E', $res[0]['coding']);
                    return $this->resSuccess(0,$erp_msg_res);
                }
            }

            return $this->resSuccess($res);
        }catch (\Exception $e2) {
            // 报错写入日志
            (new ErpBusineLogRepository())->save(['id'=>$ErpBusineLogRepository['id'],'returnTransmission'=> $e2->getMessage(),'is_success'=>3]);
            return $this->resFailed(600, '服务器错误，联系管理员');
        }
    }

    /**
     * 销售订单详情
     * @Author Lzt
     */
    public function detail(Request $request)
    {
        $data = $request->only('id');

        if (empty($data['id'])) {
            return $this->resFailed(414, 'ID不能为空');
        }
        //获取用户标识
        $user_id = $this->user->id;
        if (empty($user_id)) {
            return $this->resFailed(414, '请联系管理员');
        }

        $phone = $this->user->mobile;
        if (empty($phone)) {
            return $this->resFailed(414, '请联系管理员');
        }
        $busines_coding = "salesOrder";
        // 获取当前url
        $path = $request->path();
        $param = $request->all();
        try {
            // 打印日志
            $busine_id = (new ErpBusinesRepository())->first(['busines_coding' => $busines_coding])->id ?? '';
            $ErpBusineLogRepository =  (new ErpBusineLogRepository())->save(['busine_id'=>$busine_id,'name'=>'销售订单-详情','transmission'=>$param,'seller_accounts_id'=>$this->user->id,'seller_accounts_source'=>7,'url'=>$path,'is_success'=>2]);

            $res = ErpSalesOrder::select('erp_sales_orders.*','shops.shop_name as shop_name','wx_userinfos.nickname as sales_man_name','erp_sales_shipments.invoice_number as receipt_invoice_number','erp_courier.name as transport_name','erp_sales_mans.user_id as sales_man_user_id','shops.sys_mbol')
                ->where(['erp_sales_orders.id' => $data['id']])
                ->leftJoin('shops','shops.id','=','erp_sales_orders.shop_id')
                ->leftJoin('erp_sales_mans','erp_sales_mans.id','=','erp_sales_orders.sales_man_id')
                ->leftJoin('user_accounts','erp_sales_mans.user_id','=','user_accounts.id')
                ->leftJoin('wx_userinfos','wx_userinfos.user_id','=','user_accounts.id')
                ->leftJoin('erp_sales_shipments','erp_sales_shipments.id','=','erp_sales_orders.sales_shipment_id')
                ->leftJoin('erp_courier','erp_courier.id','=','erp_sales_orders.transport_id')
                ->first();

            if (!empty($res)) {

                $ErpRoleRepository = new ErpRoleRepository;
                $shopRoleList = $ErpRoleRepository->defaultInfoShopRole($phone,$busines_coding,$res['shop_id']);
                if (empty($shopRoleList)) {
                    return $this->resFailed(414, '没有权限');
                }
                if ($shopRoleList['is_visible'] == 3) {
                   return $this->resFailed(414, '没有权限');
                }

                $res['seller_accounts_name'] = '';
                $res['merchant_number']      = '';
                $res['merchant_name']        = '';
                $res['merchant_id']          = '';
                $seller_accounts_name = (new UserAccountRepository)->sellerMerchant($res['seller_accounts_id'],$res['seller_accounts_source'],$res['shop_id']);
                if (!empty($seller_accounts_name)) {
                    $res['seller_accounts_name'] = $seller_accounts_name['username'];
                    $res['merchant_number']      = $seller_accounts_name['merchant_number'];
                    $res['merchant_name']        = $seller_accounts_name['merchant_name'];
                    $res['merchant_id']          = $seller_accounts_name['merchant_id'];

                }

                $detail_lists = ErpSalesOrderDetail::select('erp_sales_order_details.*','goods.crm_number','goods.ljx_wine_base','seller_infos.merchant_name','seller_infos.id as merchant_id','erp_storehouse.name as store_name')->where('sales_order_id',$res['id'])
                            ->leftJoin('goods','goods.id','=','erp_sales_order_details.goods_id')
                            ->leftJoin('seller_infos','seller_infos.merchant_number','=','erp_sales_order_details.merchant_number')
                            ->leftJoin('erp_storehouse','erp_storehouse.id','=','erp_sales_order_details.store_id')
                            ->orderBy('erp_sales_order_details.id','asc')
                            ->get();

                if (!empty($detail_lists)) {
                    foreach ($detail_lists as $k => $v) {
                        $sales_price = $v['sales_price'];
                        $cost_price = $v['cost_price'];
                        $sales_num = $v['sales_num'];

                        if (empty($sales_price)) {
                            $sales_price = 0;
                        }
                        if (empty($cost_price)) {
                            $cost_price = 0;
                        }
                        if (empty($sales_num)) {
                            $sales_num = 0;
                        }
                        $profit = round(($sales_price - $cost_price)*$sales_num,2);

                        $v['profit'] = $profit;
                    }
                }
               
                $res['detail_lists'] = $detail_lists;

                $res['order_list'] = $this->extractTrackingNumbers($res['freight_number']);

            }
            // 回调成功写入日志
            (new ErpBusineLogRepository())->save(['id'=>$ErpBusineLogRepository['id'],'returnTransmission'=> $res,'invoice_number'=>$res['invoice_number'],'is_success'=>1,'shop_id'=>$res['shop_id']]);
            return $this->resSuccess($res);
        }catch (\Exception $e2) {
            // 报错写入日志
            (new ErpBusineLogRepository())->save(['id'=>$ErpBusineLogRepository['id'],'returnTransmission'=> $e2->getMessage(),'is_success'=>3]);
            return $this->resFailed(600, '服务器错误，联系管理员');
        }
    }

    /**
     * 读取快件单号
     * @param $input
     * @return array
     * @Author Eva
     */
    public function extractTrackingNumbers($input) {
        // 将输入的字符串按空白字符（空格、制表符、换行符等）拆分成数组
        $parts = preg_split('/\s+/', $input);
        $trackingNumbers = [];

        // 遍历每个部分
        foreach ($parts as $part) {
            // 如果部分包含逗号，则进一步拆分
            if (strpos($part, ',') !== false) {
                $subParts = explode(',', $part);
                foreach ($subParts as $subPart) {
                    if (!empty($subPart) && strpos($subPart, 'SF') === 0 && ctype_digit(substr($subPart, 2))) {
                        $trackingNumbers[] = $subPart;
                    }
                }
            } else {
                // 检查是否以 "SF" 开头并且后面是数字
                if (!empty($part) && strpos($part, 'SF') === 0 && ctype_digit(substr($part, 2))) {
                    $trackingNumbers[] = $part;
                }
            }
        }

        return $trackingNumbers;
    }

    /**
     * 更改状态
     * @Author Lzt
     */
    public function updateStatus(Request $request, ErpSalesOrderRepository $repository)
    {
        $data = $request->only('id', 'type');


        if (empty($data['id'])) {
            return $this->resFailed(414, 'ID不能为空');
        }

        if (!isset($data['type'])) {
            return $this->resFailed(414, '类型不能为空');
        }
        // type 类型   0：提交校验，1：撤销校验   2：审核校验:3：反审核校验
        if (!in_array($data['type'], [0, 1 ,2, 3])) {
            return $this->resFailed(414, '类型数据错误');
        }

        if ($data['type'] == 1) {
            $msg = "撤销";
            $mag_n = 'A';
        }else if ($data['type'] == 2) {
            $msg = "审核";
            $mag_n = 'C';
        }else if ($data['type'] == 3) {
            $msg = "反审核";
            $mag_n = 'D';
        }else{
            $msg = "提交";
            $mag_n = 'B';
        }

        $busines_coding = "salesOrder";
        // 获取当前url
        $path = $request->path();
        $param = $request->all();
        $rep_msg = new ErpMessageRepository();
        try {
             // 打印日志
            $busine_id = (new ErpBusinesRepository())->first(['busines_coding' => $busines_coding])->id ?? '';
            $ErpBusineLogRepository =  (new ErpBusineLogRepository())->save(['busine_id'=>$busine_id,'name'=>'销售订单-'.$msg,'transmission'=>$param,'seller_accounts_id'=>$this->user->id,'seller_accounts_source'=>7,'url'=>$path,'is_success'=>2]);

            // 验证数组
            $id_array = explode(",", $data['id']);
            $id_array = array_unique($id_array);
            $tmp_id    = [];
            $tmp_msg   = [];
            $data_info = ErpSalesOrder::whereIn('id', $id_array)->select('id','shop_id', 'invoice_number')->get()->toArray();
            foreach ($data_info as $item){
                $is_lock =$this->OrderIsLock(['shop_id' => $item['shop_id'], 'coding' => $item['invoice_number']]);
                if($is_lock){
                    if($is_lock->user_id != $this->user->id) {
                        $tmp_id[] = $item['id'];
                        $tmp_msg[] = [
                            'id' => $item['id'],
                            'msg' => '该订单已锁定，不可操作',
                            'name' => '',
                            'coding' => $item['invoice_number'],
                            'commit' => false,
                        ];
                    }
                }
            }
            // 找出差集合，差集合则是需要处理的
            $ids = array_diff($id_array, $tmp_id);
            $type = $data['type'];

            //获取用户标识
            $user_id = $this->user->id;
            if (empty($user_id)) {
                return $this->resFailed(414, '请联系管理员');
            }

            $phone = $this->user->mobile;
            if (empty($phone)) {
                return $this->resFailed(414, '请联系管理员');
            }

            //查询所有的区域
            //        $ids = explode(",", $data['id']);
            //        $ids = array_unique($ids);
            $erpSalesOrder = ErpSalesOrder::whereIn('id',$ids)->select('shop_id')->groupBy('shop_id')->get()->toArray();
            if (count($erpSalesOrder) == 0) {
                return $this->resFailed(414, '数据错误');
            }
            $busines_coding = "salesOrder";
            $business_id = ErpBusines::where('busines_coding',$busines_coding)->first();
            if (empty($business_id)) {
                return $this->resFailed(403, "请配置业务对象");
            }
            $business_id = $business_id['id'];
            // 获取当前url
            $path = $request->path();
           
            //获取当前用户的区域权限
            $ErpRoleRepository = new ErpRoleRepository;
            $shop_id = [];
            foreach ($erpSalesOrder as $k=> $v) {
                $shopRoleList = $ErpRoleRepository->defaultInfoPathShopRole($phone,$busines_coding,$v['shop_id'],$path,$data['type']);
                if (!empty($shopRoleList)) {
                    $shop_id[] = $v['shop_id'];
                }
                
            }
            if (count($shop_id) == 0) {
                return $this->resFailed(414, '没有权限');
            }

             // type 类型   0：提交校验，1：撤销校验   2：审核校验:3：反审核校验
            $res = $repository->updateStatus($data,$shop_id);
            // 合并msg
            $res = array_merge($res, $tmp_msg);

            // 回调成功写入日志
            ErpBusineLogJob::dispatch(['repository' => new ErpSalesOrder,'returnTransmission' => $res,'shop_type' => 'shop_id','busine_id'=>$busine_id,'name'=>'销售订单-'.$msg,'transmission'=>$param,'seller_accounts_id'=>$this->user->id,'seller_accounts_source'=>7,'url'=>$path,'is_success'=>1]);
            

            if (count($res) ==1) {
                if ($res[0]['commit'] == false) {
                    return $this->resFailed(414, $res[0]['msg']);
                }else{
                    $erp_msg_res = $rep_msg->getMsg('erp_sales_order', $mag_n, $res[0]['coding']);
                    return $this->resSuccess(0,$erp_msg_res);
                }
            }
            return $this->resSuccess($res);
        }catch (\Exception $e2) {
            // 报错写入日志
            (new ErpBusineLogRepository())->save(['id'=>$ErpBusineLogRepository['id'],'returnTransmission'=> $e2->getMessage(),'is_success'=>3]);
            return $this->resFailed(600, '服务器错误，联系管理员');
        }
       
    }

    /**
     * 下推 添加进入销售入库表
     * @Author Lzt
     */
    public function pushDown(Request $request, ErpSalesOrderRepository $repository)
    {
        $data = $request->only('id');
        //获取用户标识
        $user_id = $this->user->id;
        if (empty($user_id)) {
            return $this->resFailed(414, '请联系管理员');
        }

        $phone = $this->user->mobile;
        if (empty($phone)) {
            return $this->resFailed(414, '请联系管理员');
        }

        $busines_coding = "salesOrder";
        // 获取当前url
        $path = $request->path();
        $param = $request->all();

        try {

            // 打印日志
            $busine_id = (new ErpBusinesRepository())->first(['busines_coding' => $busines_coding])->id ?? '';
            $ErpBusineLogRepository =  (new ErpBusineLogRepository())->save(['busine_id'=>$busine_id,'name'=>'销售订单-下推','transmission'=>$param,'seller_accounts_id'=>$this->user->id,'seller_accounts_source'=>7,'url'=>$path,'is_success'=>2]);

            //查询所有的区域
            $ids = explode(",", $data['id']);
            $ids = array_unique($ids);
            $ErpSalesOrder = ErpSalesOrder::whereIn('id',$ids)->select('shop_id')->groupBy('shop_id')->get()->toArray();

            if (count($ErpSalesOrder) == 0) {
                return $this->resFailed(414, '数据错误');
            }
            $busines_coding = "salesShipment";
            $business_id = ErpBusines::where('busines_coding',$busines_coding)->first();
            if (empty($business_id)) {
                return $this->resFailed(403, "请配置业务对象");
            }
            $business_id = $business_id['id'];
            // 如果有出库单保存权限
            $path = "shop/v1/erpSalesShipment/save";

            //获取当前用户的区域权限
            $ErpRoleRepository = new ErpRoleRepository;
            $shop_id = [];
            foreach ($ErpSalesOrder as $k=> $v) {
                $shopRoleList = $ErpRoleRepository->defaultInfoPathShopRole($phone,$busines_coding,$v['shop_id'],$path);
                if (!empty($shopRoleList)) {
                    $shop_id[] = $v['shop_id'];
                }
                
            }
            if (count($shop_id) == 0) {
                return $this->resFailed(414, '没有权限');
            }

            $seller_accounts_source   = 7;
            $res = $repository->pushDown($data['id'],$shop_id,$user_id,$seller_accounts_source);

            if (empty($res)) {
                return $this->resFailed(414, '数据异常');
            }

            // 回调成功写入日志
            ErpBusineLogJob::dispatch(['repository' => new ErpSalesOrder,'returnTransmission' => $res,'shop_type' => 'shop_id','busine_id'=>$busine_id,'name'=>'销售订单-下推','transmission'=>$param,'seller_accounts_id'=>$this->user->id,'seller_accounts_source'=>7,'url'=>$path,'is_success'=>1]);
            
            if (count($res) ==1) {
                if ($res[0]['commit'] == false) {
                    return $this->resFailed(414, $res[0]['msg']);
                }else{
                    return $this->resSuccess(0,'下推成功');
                }
            }
            return $this->resSuccess($res);

        }catch (\Exception $e2) {
             // 报错写入日志
            (new ErpBusineLogRepository())->save(['id'=>$ErpBusineLogRepository['id'],'returnTransmission'=> $e2->getMessage(),'is_success'=>3]);

            return $this->resFailed(600, '服务器错误，联系管理员');
        }
    }

     /**
     * 导入
     * @Author Lzt
     */
    public function import(Request $request, ErpSalesOrderRepository $repository)
    {
        ini_set('memory_limit', '-1');
        set_time_limit(0);

        $phone      = $this->user->mobile;
        //获取用户标识
        $user_id = $this->user->id;
        if (empty($user_id)) {
            return $this->resFailed(414, '请联系管理员');
        }
        if (empty($phone)) {
            return $this->resFailed(414, '请联系管理员');
        }
        $erpRoleRepository = new ErpRoleRepository;
        $shop_ids = $erpRoleRepository->shopPhone($phone);
    
        if (empty($shop_ids)) {
            return $this->resFailed(414, '区域为空');
        }

        $busines_coding = "purchaseOrder";
        $res = ErpBusines::where('busines_coding',$busines_coding)->first();
        if (empty($res)) {
            return $this->resFailed(403, "请配置业务对象");
        }
        $number = (new CodingService)->generaCodingV1($res['id']);
        if ($number['text'] != "ok") {
            return $this->resFailed(403, "请去配置系统编码规则");
        }

        $file  = $request->file('file');
        if (empty($file)) {
            return $this->resFailed(414, '文件为空');
        }

        $filePath = $repository ->upload($file);
        if (empty($res)) {
            return $this->resFailed(414, '导入失败');
        }
        // 加载Excel文件
        $spreadsheet = IOFactory::load($filePath);
         
        // 获取名为'销售订单'的工作页
        $worksheet = $spreadsheet->getSheetByName('销售订单');

        // 检查工作表是否存在
        if ($worksheet !== null) {

            $rowIterator = $worksheet->getRowIterator();

            // 获取总行数
            $highestRow = $worksheet->getHighestRow();
            $res = [];
            $empty_num = 0;
            foreach ($rowIterator as $k => $row) {
                if ($k == 1) {
                    continue;
                }
                //100行全部为空 就终止
                if ($empty_num == 100) {
                    break;
                }
                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false); // 遍历所有单元格
                $data=[];
                foreach ($cellIterator as $k1 => $cell) {
                    
                    $asciiValue = $repository->asciiValue($k1);
                    if ($asciiValue == false) {
                        break;
                    }
                   
                    if ($k1 == "E") {
                        $value = $cell->getValue();
                        if (is_numeric($value)) { 
                            $toTimestamp = Date::excelToTimestamp($value); 
                            $value = date('Y-m-d H:i:s', $toTimestamp ); 
                        }
                    }else{
                        $value = $cell->getValue();
                    }


                    $data[] = $value;
                }

                //判断值是否全部为空
                $allValuesEmpty = $repository->allValuesEmpty($data);
                if ($allValuesEmpty == true) {
                    $empty_num = $empty_num+1;
                }else{
                    $res[]=$data;
                }
            }
        } else {
            return $this->resFailed(414, '工作表不存在');
        }

    
        if (count($res) == 0) {
            return $this->resFailed(414, '数据完全为空');
        }
  

           
        //赋建给res
        $res_key = ['invoice_number','organization_coding','shop_name','sales_man_name','sales_date', 'customer_name','phone','province_name','address','transport_name','freight_number','information','note','crm_number','wine_style_wine_ch','wine_style_wine_en','year_name','size_name','inventory_unit_name','sales_num','sales_price','store_coding','store_name','inventory_status','store_note'];

      

        $res_list = [];
        for ($i=0; $i <count($res) ; $i++) { 
            $res1 =  array_combine($res_key,$res[$i]);
            $res_list[] = $res1;
        }
        $order_list = [];
        $is_detail = 1;
        $k1 = 0;
        $k2 = 0;

        //订单信息为完全是空的，则上下为同为当前的订单详情 组合数组
        $count_list =count($res_list);
        foreach ($res_list as $k => $v) {

            if ($k == 0) {
                $order_list[$k1]['invoice_number']          = $v['invoice_number'];
                $order_list[$k1]['organization_coding']     = $v['organization_coding'];
                $order_list[$k1]['shop_name']               = $v['shop_name'];
                $order_list[$k1]['sales_man_name']          = $v['sales_man_name'];
                $order_list[$k1]['sales_date']              = $v['sales_date'];
                $order_list[$k1]['customer_name']           = $v['customer_name'];
                $order_list[$k1]['phone']                   = $v['phone'];
                $order_list[$k1]['province_name']           = $v['province_name'];
                $order_list[$k1]['address']                 = $v['address'];
                $order_list[$k1]['transport_name']          = $v['transport_name'];
                $order_list[$k1]['freight_number']          = $v['freight_number'];
                $order_list[$k1]['information']             = $v['information'];
                $order_list[$k1]['note']                    = $v['note'];
                $order_list[$k1]['err_mes']                 =  "";
                $order_list[$k1]['seller_accounts_id']      =  $user_id;
                $order_list[$k1]['seller_accounts_source']  =  7;

                $detail_lists[$k2]['crm_number']            = $v['crm_number'];
                $detail_lists[$k2]['wine_style_wine_ch']    =  $v['wine_style_wine_ch'];
                $detail_lists[$k2]['wine_style_wine_en']    =  $v['wine_style_wine_en'];
                $detail_lists[$k2]['year_name']             =  $v['year_name'];
                $detail_lists[$k2]['size_name']             =  $v['size_name'];
                $detail_lists[$k2]['inventory_unit_name']   =  $v['inventory_unit_name'];
                $detail_lists[$k2]['sales_num']             =  $v['sales_num'];
                $detail_lists[$k2]['sales_price']           =  $v['sales_price'];
                $detail_lists[$k2]['store_coding']          =  $v['store_coding'];
                $detail_lists[$k2]['store_name']            =  $v['store_name'];
                $detail_lists[$k2]['inventory_status']      =  $v['inventory_status'];
                $detail_lists[$k2]['store_note']            =  $v['store_note'];
                if ($count_list - $k =1) {
                    $order_list[$k1]['detail_lists'] = $detail_lists;
                }
                $k2 = $k2+1;
            }else{
                if (empty($v['invoice_number'])&&empty($v['organization_coding'])&&empty($v['shop_name'])&&empty($v['sales_man_name'])&&empty($v['sales_date'])&&empty($v['customer_name'])&&empty($v['province_name'])&&empty($v['supplier_name'])&&empty($v['transport_name'])&&empty($v['freight_number'])&&empty($v['information'])&&empty($v['note'])) {
                // 订单信息为完全是空的，则上下为同为当前的订单详情
                    $detail_lists[$k2]['crm_number']            = $v['crm_number'];
                    $detail_lists[$k2]['wine_style_wine_ch']    =  $v['wine_style_wine_ch'];
                    $detail_lists[$k2]['wine_style_wine_en']    =  $v['wine_style_wine_en'];
                    $detail_lists[$k2]['year_name']             =  $v['year_name'];
                    $detail_lists[$k2]['size_name']             =  $v['size_name'];
                    $detail_lists[$k2]['inventory_unit_name']   =  $v['inventory_unit_name'];
                    $detail_lists[$k2]['sales_num']             =  $v['sales_num'];
                    $detail_lists[$k2]['sales_price']           =  $v['sales_price'];
                    $detail_lists[$k2]['store_coding']          =  $v['store_coding'];
                    $detail_lists[$k2]['store_name']            =  $v['store_name'];
                    $detail_lists[$k2]['inventory_status']      =  $v['inventory_status'];
                    $detail_lists[$k2]['store_note']            =  $v['store_note'];

                    if ($count_list - $k =1) {
                        $order_list[$k1]['detail_lists'] = $detail_lists;
                    }
                    $k2 = $k2+1;
                }else{
                    //重置k2 detail_lists清空 $k1+1
                    $k2 = 0;
                    $k1 = $k1+1;
                    $detail_lists = [];
                    $order_list[$k1]['invoice_number']          = $v['invoice_number'];
                    $order_list[$k1]['organization_coding']     = $v['organization_coding'];
                    $order_list[$k1]['shop_name']               = $v['shop_name'];
                    $order_list[$k1]['sales_man_name']          = $v['sales_man_name'];
                    $order_list[$k1]['sales_date']              = $v['sales_date'];
                    $order_list[$k1]['customer_name']           = $v['customer_name'];
                    $order_list[$k1]['phone']                   = $v['phone'];
                    $order_list[$k1]['province_name']           = $v['province_name'];
                    $order_list[$k1]['address']                 = $v['address'];
                    $order_list[$k1]['transport_name']          = $v['transport_name'];
                    $order_list[$k1]['freight_number']          = $v['freight_number'];
                    $order_list[$k1]['information']             = $v['information'];
                    $order_list[$k1]['note']                    = $v['note'];
                    $order_list[$k1]['err_mes']                 =  "";
                    $order_list[$k1]['seller_accounts_id']      =  $user_id;
                    $order_list[$k1]['seller_accounts_source']  =  7;

                    $detail_lists[$k2]['crm_number']            = $v['crm_number'];
                    $detail_lists[$k2]['wine_style_wine_ch']    =  $v['wine_style_wine_ch'];
                    $detail_lists[$k2]['wine_style_wine_en']    =  $v['wine_style_wine_en'];
                    $detail_lists[$k2]['year_name']             =  $v['year_name'];
                    $detail_lists[$k2]['size_name']             =  $v['size_name'];
                    $detail_lists[$k2]['inventory_unit_name']   =  $v['inventory_unit_name'];
                    $detail_lists[$k2]['sales_num']             =  $v['sales_num'];
                    $detail_lists[$k2]['sales_price']           =  $v['sales_price'];
                    $detail_lists[$k2]['store_coding']          =  $v['store_coding'];
                    $detail_lists[$k2]['store_name']            =  $v['store_name'];
                    $detail_lists[$k2]['inventory_status']      =  $v['inventory_status'];
                    $detail_lists[$k2]['store_note']            =  $v['store_note'];

                    if ($count_list - $k =1) {
                        $order_list[$k1]['detail_lists'] = $detail_lists;
                    }
                    $k2 = $k2+1;
                }
            }
        }

        //验证数据
        $importProcessingData = $repository ->importProcessingData($order_list,$shop_ids,$phone);

        if ($importProcessingData['code'] == 0) {
            return $this->resSuccess(0,$importProcessingData['msg']);
        }else{
            return $this->resFailed(414,'导入失败', $importProcessingData);
        }
    }

    /**
     * 生成编码-递归10次
     * @param $business_id
     * @param $invoice_number
     * @param $num
     */
    public function getCoding($business_id,$invoice_number,$num)
    {
        if (empty($invoice_number)) {
            return "";
        }
        $ErpSalesOrder = ErpSalesOrder::where('invoice_number',$invoice_number)->first();
        if (empty($ErpSalesOrder)) {
            return $invoice_number;
        }

        if ($num < 10) {
            $num = $num+1;
            $number = (new CodingService)->generaCodingV1($business_id);
            if ($number['text'] != "ok") {
                return "";
            }
            $invoice_number = $number['number'];

            $res =  $this->getCoding($business_id,$num,$invoice_number);
            if (empty($res)) {
                 return $invoice_number;
            }else{
                return $this->getCoding($business_id,$num,$invoice_number);
            }

        }
        return "";
    }


      /**
     * 销售验证详情信息
     */
    public function validationDetail()
    {
       
        $res =  ErpSalesOrder::leftJoin('erp_sales_order_details','erp_sales_orders.id','=','erp_sales_order_details.sales_order_id')
            ->leftJoin('goods','goods.id','=','erp_sales_order_details.goods_id')
            ->leftJoin('shops','shops.id','=','erp_sales_orders.shop_id')
            ->leftJoin('erp_sales_mans','erp_sales_mans.id','=','erp_sales_orders.sales_man_id')
            ->leftJoin('user_accounts','erp_sales_mans.user_id','=','user_accounts.id')
            ->leftJoin('wx_userinfos','wx_userinfos.user_id','=','user_accounts.id')
            ->leftJoin('seller_infos','seller_infos.merchant_number','=','erp_sales_order_details.merchant_number')
            ->leftJoin('erp_storehouse','erp_storehouse.id','=','erp_sales_order_details.store_id')
            ->leftJoin('erp_sales_shipments','erp_sales_shipments.id','=','erp_sales_orders.sales_shipment_id')
            ->leftJoin('erp_province','erp_province.id','=','erp_sales_orders.province')
            ->leftJoin('erp_courier','erp_courier.id','=','erp_sales_orders.transport_id')
            ->select('erp_sales_orders.*','shops.shop_name as shop_name','wx_userinfos.nickname as sales_man_name','erp_storehouse.name as store_name','goods.crm_number','erp_sales_order_details.wine_style_name','erp_sales_order_details.year_name','erp_sales_order_details.size_name','erp_sales_order_details.inventory_unit_name','erp_sales_order_details.sales_num','erp_sales_order_details.cost_price','erp_sales_order_details.sales_price','erp_sales_order_details.total','seller_infos.merchant_name','erp_sales_order_details.note as detail_note','erp_sales_order_details.goods_id','seller_infos.merchant_number','seller_infos.id as merchant_id','erp_sales_shipments.invoice_number as relevance_invoice_number','erp_sales_order_details.inventory_status','erp_province.name as province_name','erp_courier.name as transport_name','erp_sales_order_details.old_cost_price','shops.sys_mbol','erp_sales_order_details.wine_style_wine_ch','erp_sales_order_details.wine_style_wine_en','erp_sales_order_details.id as details_id','goods.goods_name','erp_sales_order_details.profit')
            ->groupBy('erp_sales_order_details.id')
            ->orderBy('erp_sales_orders.id','desc')
            ->get()->toArray();
        foreach ($res as $k => $v) {
             //计算金额
                if (empty($v['sales_price'])) {
                    $v['sales_price'] = 0;
                }
                if (empty($v['cost_price'])) {
                    $v['cost_price'] = 0;
                }
                if (empty($v['sales_num'])) {
                    $v['sales_num'] = 0;
                }
                $profit = round(($v['sales_price'] - $v['cost_price'])*$v['sales_num'],2);
                $total = round($v['sales_price']*$v['sales_num'],2);
                $msg="";

                if ($v['profit'] != $profit) {
                    $msg = $msg ." 利润错误：应该是".$profit;
                   

                }

                if ($v['total'] != $total) {
                    $msg = $msg ." 金额错误：应该是".$total;
                   
                }

                $detail = ErpSalesOrderDetail::select('id','sales_num','sales_price','cost_price','total','profit')->where('sales_order_id',$v['id'])->get();
                if (!empty($detail)) {
                    $all_total = 0;
                        $all_num = 0;
                        $all_profit = 0;
                    foreach ($detail as $k1 => $v1) {

                        if (empty($v1['sales_price'])) {
                            $v1['sales_price'] = 0;
                        }
                        if (empty($v1['cost_price'])) {
                            $v1['cost_price'] = 0;
                        }
                        if (empty($v1['sales_num'])) {
                            $v1['sales_num'] = 0;
                        }

                            $profit = round(($v1['sales_price'] - $v1['cost_price'])*$v1['sales_num'],2);
                            $total = round($v1['sales_price']*$v1['sales_num'],2);
                            $all_num = $all_num + $v1['sales_num'];
                            $all_total = round($all_total + $total,2);
                            $all_profit = round($all_profit + $profit,2);
                    }
                    if ($v['all_total']!=$all_total) {
                        $msg = $msg ." 总金额错误：应该是".$all_total;
                    }
                    if ($v['all_num']!=$all_num) {
                        $msg = $msg ." 总数量错误：应该是".$all_num;
                    }
                    if ($v['all_profit']!=$all_profit) {
                        $msg = $msg ." 总利润错误：应该是".$all_profit;
                    }
                }

                if (!empty($msg)) {
                    $res[$k]['msg'] = $msg;
                     continue;
                }
                unset($res[$k]);
        }
        $res = array_values($res);
        // return $errList;
            // return $res;
         if (!empty($res)) {
            //上下id一样的去除部分
            foreach ($res as $k => $v) {
                $v['seller_accounts_name'] = '';
                $seller_accounts_name = (new UserAccountRepository)->sellerAccountName($v['seller_accounts_id'],$v['seller_accounts_source']);
                if (!empty($seller_accounts_name)) {
                    $v['seller_accounts_name'] = $seller_accounts_name['username'];
                }
                if ($k == 0) {
                    continue;
                }
                $k1 = $k-1;
                if ($res[$k]['id'] == $res[$k1]['id']) {
                    $v['status'] = "";
                    $v['shipment_status'] = "";
                    $v['down_status'] = "";
                    $v['invoice_number'] = "";
                    $v['shop_name'] = "";
                    $v['sales_man_name'] = "";
                    $v['all_total'] = "";
                    $v['all_num'] = "";
                    $v['all_profit'] = "";
                    $v['sales_date'] = null;
                    $v['shipment_date'] = null;
                    $v['shipment_status_name'] = "";
                    $v['information'] = "";
                    $v['customer_name'] = "";
                    $v['phone'] = "";
                    $v['province_name'] = "";
                    $v['address'] = "";
                    $v['transport_name'] = "";
                    $v['freight'] = "";
                    $v['freight_number'] = "";
                    $v['note'] = "";
                    $v['status_name'] = "";
                    $v['review_date'] = null;
                    $v['created_at'] = null;
                    $v['updated_at'] = null;
                    $v['down_status_name'] = "";
                }
            }
        }
        $data = [];
        foreach ($res as $item) {
            $data[] = [
                $item['shop_name'],
                $item['sales_date'],
                $item['crm_number'],
                $item['invoice_number'],
                $item['status_name'],
                $item['sales_man_name'],
                $item['customer_name'],
                $item['wine_style_wine_ch'].$item['wine_style_wine_en'],
                $item['year_name'],
                $item['size_name'],
                $item['inventory_unit_name'],
                $item['sales_num'],
                $item['sales_price'],
                $item['profit'],
                $item['cost_price'],
                $item['all_profit'],
                $item['all_total'],
                $item['transport_name'],
                $item['freight'],
                $item['freight_number'],
                $item['inventory_status'],
                $item['note'],
                $item['phone'],
                $item['province_name'],
                $item['address'],
                $item['total'],
                $item['all_num'],
                $item['store_name'],
                $item['shipment_date'],
                $item['shipment_status_name'],
                $item['down_status_name'],
                $item['information'],
                $item['detail_note'],
                $item['created_at'],
                $item['updated_at'],
                $item['review_date'],
                $item['merchant_name'],
                $item['msg'],
            ];
        }

        $headings = [
            '销售组织', '销售日期', '商品编码', '单据编码', '单据状态', '销售员' , '联系人' , '酒款名称' , '年份', '规格', '包装',
            '销售数量',  '销售价格', '利润', '成本', '总利润', '总金额', '运输方式', '运费', '运输单号', '库存状态', '备注', '电话', '省份','详细地址',
            '金额', '总数量' , '仓库' , '出库日期', '出库状态', '下推状态', '自提信息', '仓库备注', '创建日期', '更新日期' , '审核日期', '商家'
        ];
         // 导出
        return Excel::download(new UsersExport($data, $headings), '采购入库导出数据'.date('Y-m-d H:i:s').'.xlsx');

// return $res;

       
    }


    /**
     * 查询用户时正在编辑的订单
     */
    public function OrderIsLock(array $array)
    {
        return ErpConflictList::where('shop_id', '=', $array['shop_id'])
            ->where('coding', '=', $array['coding'])
            ->where('control_type', '=', '业务操作互斥')
            ->where('control_name' ,'=', '销售订单-编辑')
            ->first();
    }


}
